<?php

namespace App\Observers;

use App\Jobs\DeliverProduct;
use App\Models\Order;
use App\Models\UniDeliverProductNotification;
use App\Models\VendingMachine;

class UniDeliverProductNotificationObserver
{
    public function created(UniDeliverProductNotification $uniDeliverProductNotification)
    {
        $vendingMachine = VendingMachine::where('code', $uniDeliverProductNotification->machine_id)->first();
        DeliverProduct::dispatch($uniDeliverProductNotification, $vendingMachine->machine_api_type)->onQueue($vendingMachine->code);
        dispatch(function () use ($uniDeliverProductNotification) {
            if ($uniDeliverProductNotification->result === 'delivering' || $uniDeliverProductNotification->result === 'queueing') {
                $uniDeliverProductNotification->update(['result' => 'timeout']);
                if ($order = $uniDeliverProductNotification->order) {
                    $order->update(['deliver_status' => Order::DELIVER_STATUS_TIMEOUT]);
                }
            }
        })->delay(now()->addSeconds(300));
    }

    public function updated(UniDeliverProductNotification $uniDeliverProductNotification)
    {
        if ($order = $uniDeliverProductNotification->order) {
            if (!stripos($uniDeliverProductNotification->order_no, 'a')) {
                if ($uniDeliverProductNotification->result === 'SUCCESS') {
                    $order->update(['deliver_status' => Order::DELIVER_STATUS_DELIVERED]);
                } elseif ($uniDeliverProductNotification->result === 'FAIL') {
                    $order->update(['deliver_status' => Order::DELIVER_STATUS_FAILED]);
                }
            } else {
                if (isset($uniDeliverProductNotification->extra['last']) && $uniDeliverProductNotification->result !== 'delivering') {
                    if ($order->uniDeliverProductNotifications->where('result', '1')->count() === $order->uniDeliverProductNotifications->count()) {
                        $order->update(['deliver_status' => Order::DELIVER_STATUS_DELIVERED]);
                    } elseif ($order->uniDeliverProductNotifications->where('result', 'timeout')->count() > 0) {
                        $order->update(['deliver_status' => Order::DELIVER_STATUS_TIMEOUT]);
                    } elseif ($order->uniDeliverProductNotifications->where('result', '2')->count() > 0) {
                        $order->update(['deliver_status' => Order::DELIVER_STATUS_TIMEOUT]);
                    } elseif ($order->uniDeliverProductNotifications->where('result', '3')->count() > 0) {
                        $order->update(['deliver_status' => Order::DELIVER_STATUS_FAILED]);
                    }
                }
            }
        }
    }
}
